package com.youkeda.test.netty.client;

import com.youkeda.test.netty.handler.ClientHandlerSimple;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

/**
 * @author CoderXshuai
 */
public class ClientSimple {

    // 本地服务端
    private static final String SERVER_IP = "127.0.0.1";
    // 本地服务端的端口号
    private static final int PORT = getPort();
    // 主服务端
    private static Bootstrap bootstrap = new Bootstrap();

    public void run(String msg) throws InterruptedException {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        try {
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
                            ch.pipeline().addLast(new ClientHandlerSimple(msg));
                        }
                    });

            System.out.println("连接服务器...");
            ChannelFuture future = doConnect();
            if (future != null) {
                future.channel().closeFuture();
            }
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    //  连接到服务端
    public static ChannelFuture doConnect() {
        ChannelFuture future = null;
        try {
            future = bootstrap.connect(SERVER_IP, PORT);
        } catch (Exception e) {
            System.out.println("连接异常......");
            e.printStackTrace();
        }

        return future;
    }

    private static int getPort() {
        Double port = (Math.random() + 1) * 10000;
        return port.intValue();
    }

    public static void main(String[] args) throws InterruptedException {
        String msg = "HelloWorld!  你好，世界！";

        new ClientSimple().run(msg);
    }
}
